<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  addNeedPlanApi,
  deleteNeedPlanApi,
  getNeedPlanListApi,
  putNeedPlanApi,
  recognizeNeedApi,
  triggerNeedPlanApi
} from '@/api/dispatch/needplan'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElTag, ElInput, ElButton, ElDivider, ElPopover, ElLink, ElMessage } from 'element-plus'
import { Search } from '@/components/Search'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { deepCopy } from '@/utils'
import { NeedPlanType } from '@/api/dispatch/needplan/types'

const { t } = useI18n()

const ids = ref<string[] | number[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getNeedPlanListApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list:
        res.data.map((item) => {
          return { table_items: deepCopy(item.items), ...item }
        }) || [],
      total: res.count || 0
    }
  },
  fetchDelApi: async () => {
    const res = await deleteNeedPlanApi(unref(ids))
    return !!res
  }
})

const { dataList, loading, total } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('common.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'product_type',
    label: '型号',
    form: {
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'station',
    label: '工位',
    form: {
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'start',
    label: '起始时间',
    search: {
      hidden: true
    },
    form: {
      colProps: {
        span: 12
      },
      component: 'DatePicker',
      componentProps: {
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'end',
    label: '结束时间',
    search: {
      hidden: true
    },
    form: {
      colProps: {
        span: 12
      },
      component: 'DatePicker',
      componentProps: {
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'status',
    label: '计划状态',
    form: {
      hidden: true
    },
    search: {
      component: 'Select',
      componentProps: {
        options: [
          {
            value: '收集中'
          },
          {
            value: '已下发'
          },
          {
            value: '已废弃'
          }
        ]
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElTag
                type={
                  data.row.status == '已下发'
                    ? 'success'
                    : data.row.status == '收集中'
                      ? 'info'
                      : 'danger'
                }
              >
                {data.row.status}
              </ElTag>
            </>
          )
        }
      }
    }
  },
  {
    field: 'table_items',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      label: '需求量',
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElPopover
                trigger="click"
                width="800px"
                v-slots={{
                  reference: () => {
                    return (
                      <ElLink>
                        {data.row?.table_items && data.row.table_items.length > 0 ? (
                          <ElTag type="success">{data.row.table_items.length} 项</ElTag>
                        ) : (
                          <ElTag type="info">0 项</ElTag>
                        )}
                      </ElLink>
                    )
                  },
                  default: () => {
                    const tableColumns = reactive<TableColumn[]>([
                      {
                        field: 'index',
                        label: t('common.index'),
                        type: 'index',
                        fixed: true
                      },
                      {
                        field: 'name',
                        label: '辅料名称',
                        minWidth: 120
                      },
                      {
                        field: 'type',
                        label: '辅料类型',
                        minWidth: 80
                      },
                      {
                        field: 'number',
                        label: '需求数量',
                        minWidth: 120
                      },
                      {
                        field: 'unit',
                        label: '单位',
                        minWidth: 80
                      },
                      {
                        field: 'remark',
                        label: '备注',
                        minWidth: 240
                      }
                    ])
                    return (
                      <>
                        <Table
                          data={data.row?.table_items}
                          columns={tableColumns}
                          class="w-full"
                          maxHeight="500"
                        />
                      </>
                    )
                  }
                }}
              />
            </>
          )
        }
      }
    }
  },
  // {
  //   field: 'transport_id',
  //   label: '单号',
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     hidden: true
  //   }
  // },
  {
    field: 'create_datetime',
    label: '创建时间',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'transport_datetime',
    label: '下发时间',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'remark',
    label: t('common.remark'),
    search: {
      hidden: true
    },
    form: {
      colProps: {
        span: 24
      },
      componentProps: {
        type: 'textarea'
      }
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'items',
    search: {
      hidden: true
    },
    form: {
      colProps: {
        span: 24
      },
      formItemProps: {
        slots: {
          default: (data) => {
            const tableColumns = reactive<TableColumn[]>([
              {
                field: 'index',
                label: t('common.index'),
                type: 'index',
                fixed: true
              },
              {
                field: 'name',
                label: '辅料名称',
                minWidth: 120,
                slots: {
                  default: (scope) => <ElInput v-model={scope.row!.name} />
                }
              },
              {
                field: 'type',
                label: '辅料类型',
                minWidth: 80,
                slots: {
                  default: (scope) => <ElInput v-model={scope.row!.type} />
                }
              },
              {
                field: 'number',
                label: '需求数量',
                minWidth: 120,
                slots: {
                  default: (scope) => <ElInput v-model={scope.row!.number} />
                }
              },
              {
                field: 'unit',
                label: '单位',
                minWidth: 80,
                slots: {
                  default: (scope) => <ElInput v-model={scope.row!.unit} />
                }
              },
              {
                field: 'remark',
                label: '备注',
                minWidth: 240,
                slots: {
                  default: (scope) => <ElInput v-model={scope.row!.remark} type="textarea" />
                }
              },
              {
                field: 'action',
                label: '操作',
                minWidth: 80,
                slots: {
                  default: (scope) => (
                    <ElButton onClick={() => data.items.splice(scope.$index, 1)}>删除</ElButton>
                  )
                }
              }
            ])
            const addItem = () => {
              if (!data.items) data.items = []
              data.items.push({
                type: '',
                name: '',
                number: '',
                unit: '',
                remark: ''
              })
            }
            const recognizeNeed = async () => {
              const write = unref(writeRef)
              const formData = await write?.submit()
              if (formData) {
                const res = await recognizeNeedApi(formData)
                if (res) {
                  data.items = res.data
                  ElMessage.success('识别成功')
                }
              }
            }
            return (
              <>
                <ElDivider class="mt-40">需求量收集</ElDivider>
                <ElButton type="primary" onClick={recognizeNeed} class="mb-10px">
                  识别辅料需求
                </ElButton>
                <ElButton onClick={addItem} class="mb-10px">
                  添加
                </ElButton>
                <Table data={data.items} columns={tableColumns} class="w-full" height="100%" />
              </>
            )
          }
        }
      }
    },
    detail: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('common.action'),
    // width: 160,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              {data.row!.status === '收集中' ? (
                <>
                  <ElButton link type="info" onClick={() => action(data.row, 'edit')}>
                    {'编辑'}
                  </ElButton>
                  <ElButton link type="success" onClick={() => callMethod(data.row, 'call')}>
                    {'下发'}
                  </ElButton>
                  <ElButton link type="danger" onClick={() => callMethod(data.row, 'drop')}>
                    {'废弃'}
                  </ElButton>
                </>
              ) : (
                ''
              )}
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = async (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'common.edit' : 'common.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const AddAction = () => {
  dialogTitle.value = t('common.add')
  actionType.value = 'add'
  currentRow.value = undefined
  dialogVisible.value = true
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      let res: any = undefined
      if (actionType.value === 'add') {
        res = await addNeedPlanApi(formData)
      } else if (actionType.value === 'edit') {
        res = await putNeedPlanApi(formData)
      }
      if (res) {
        dialogVisible.value = false
        getList()
      }
    } finally {
      saveLoading.value = false
    }
  }
}

const callMethod = async (row: any, method: string) => {
  try {
    await triggerNeedPlanApi(row.id, method)
  } finally {
    getList()
  }
}

const delLoading = ref(false)

const delData = async (row: NeedPlanType | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.id]
    : elTableExpose?.getSelectionRows().map((v: NeedPlanType) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <div class="mb-10px">
      <ElButton type="primary" @click="AddAction">{{ t('common.add') }}</ElButton>
      <!--      <ElButton type="primary" @click="AddAction">{{ '导出' }}</ElButton>-->
      <ElButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('common.del') }}
      </ElButton>
    </div>
    <Table
      :columns="allSchemas.tableColumns"
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write ref="writeRef" :current-row="currentRow" :form-schema="allSchemas.formSchema" />
    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('common.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('common.close') }}</ElButton>
    </template>
  </Dialog>
</template>
